
//
//  TBLoginViewController.swift
//  新浪微博
//
//  Created by bin on 16/1/26.
//  Copyright © 2016年 XMG. All rights reserved.
//

import UIKit
import SVProgressHUD

class TBLoginViewController: UIViewController {

    @IBOutlet weak var webView: UIWebView!
        
    override func viewDidLoad() {
        super.viewDidLoad()
        webView.delegate = self
        automaticallyAdjustsScrollViewInsets = false
        loadPage()
        // Do any additional setup after loading the view.
    }


    @IBAction func fillIn(sender: UIBarButtonItem) {
        let js = "document.getElementById('userId').value = 'tb7318696@sina.com';"  + "document.getElementById('passwd').value = 'tb7318696';"
        webView.stringByEvaluatingJavaScriptFromString(js)
    }
    @IBAction func cancle(sender: UIBarButtonItem) {
        dismissViewControllerAnimated(true, completion: nil)
    }

    private func loadPage(){
        let urlStr = "https://api.weibo.com/oauth2/authorize?client_id=" + "\(App_Key)" + "&redirect_uri=" + "\(Redirect_Uri)"
        let url = NSURL(string: urlStr)!
        let request = NSURLRequest(URL: url)
        webView.loadRequest(request)
    }

    private func getAccessToken(code: String){
        let parameters = ["client_id":App_Key , "client_secret":App_Secret, "grant_type":"authorization_code", "code":code, "redirect_uri":Redirect_Uri]
        TBNetWorkTools.shareInstance.getAccessToken(parameters) { (response) -> Void in
            let userAccount = TBUserAccount(dict: response as! [String:AnyObject])
            self.loadUserInfo(userAccount)
        }
        
    }
}

extension TBLoginViewController: UIWebViewDelegate{
    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.showWithStatus("正在加载", maskType: SVProgressHUDMaskType.Black)
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {

//        TBLog("\(request.URL?.absoluteString)")
        let url = request.URL?.absoluteString
        guard let urlStr = url where urlStr.hasPrefix(Redirect_Uri) else{
//            print("发送未授权的requestToken")
            return true
        }
        guard !urlStr.containsString("error_code") else{
//            print("error_code")
            return false
        }
        
        let code = urlStr.substringFromIndex("http://www.baidu.com/?code=".endIndex)
        print("\(code)")
        getAccessToken(code)
        return true
    }
  
    private func loadUserInfo(userAccount: TBUserAccount) {
        
        let parameter = ["access_token" : userAccount.access_token!, "uid" : userAccount.uid!]
        TBNetWorkTools.shareInstance.getUserInfo(parameter, success: { (task, response) -> Void in
            userAccount.screen_name = response!["screen_name"] as? String
            userAccount.profile_image_url = response!["profile_image_url"] as? String
            userAccount.archiveToFile()
            //            print("\(response)")
            NSNotificationCenter.defaultCenter().postNotificationName(SwitchRootViewControllerNotification, object: self, userInfo: ["vc" : "welcome"])
            
            }) { (task, error) -> Void in
                print("\(error)")
        }
    }
}
